package com._54programer;

import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.io.IOException;
import java.net.InetAddress;

/**
 * 通过XContentBuilder创建文档
 */
public class DocumentTest1 {
    public static void main(String[] args)throws IOException {
        //* 1.获取客户端：设置集群名称，设置请求地址和端口TCP的
        Settings settings = Settings.builder().put("cluster.name", "elasticsearch").build();
        InetSocketTransportAddress address = new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300);
        PreBuiltTransportClient client = new PreBuiltTransportClient(settings);
        client.addTransportAddress(address);
        //* 3.创建JSON请求体:参考第一天的设置创建文档的JSON数据
        XContentBuilder jsonBuilder = XContentFactory.jsonBuilder();
        jsonBuilder.startObject()
                .field("id","1")
                .field("title","ELasticSearch是一个基于Lucene的搜索服务器")
                .field("content","content它提供了一个分布式多用户能力的全文搜索引擎，基于RESTful web接口。Elasticsearch是用Java开发的，并作为Apache许可条款下的开放源码发布，是当前流行的企业级搜索引擎。设计用于云计算中，能够达到实时搜索，稳定，可靠，快速，安装使用方便。")
                .endObject();
        //* 2.创建索引设置文档请求对象:需要设置index,type,id,请求体
        IndexRequestBuilder requestBuilder = client.prepareIndex("blog1", "article", "1");
        requestBuilder.setSource(jsonBuilder);
        //* 4.请求对象执行发送请求操作,请求完成会获取响应对象
        IndexResponse indexResponse = requestBuilder.get();
        System.out.println(indexResponse.toString());
        //* 5.关闭客户端
        client.close();

    }
}
